<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Student List Management</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    table,
    th,
    td {
      border: 1px solid black;
    }

    th,
    td {
      padding: 8px;
      text-align: left;
    }

    th {
      background-color: #f2f2f2;
    }

    /* 弹框样式 */
    .modal {
      display: none;
      /* 初始隐藏 */
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgb(0, 0, 0);
      background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 300px;
    }

    .modal-content label {
      display: block;
      margin-bottom: 5px;
    }

    .modal-content input[type="text"],
    .modal-content input[type="number"],
    .modal-content select {
      padding: 8px;
      margin-bottom: 10px;
    }

    .modal-content button {
      width: 100%;
      padding: 10px;
      background-color: #4CAF50;
      color: white;
      border: none;
      cursor: pointer;
    }

    .modal-content button:hover {
      background-color: #45a049;
    }

    .studentGender {
      width: 300px;
    }

    .studentName,
    .studentHobbies,
    .studentAge,
    .studentPhone,
    .studentEmail {
      width: 280px;
    }

    .studentTable th,
    .studentTable td,
    h2 {
      text-align: center;
    }

    .rf {
      float: right;
    }

    .search {
      margin-right: 20px;
      margin-bottom: 10px;
      border-left: none;
    }

    .searchname {
      border-right: none;
    }
  </style>
</head>

<body>

  <h2>Student List Management</h2>
  <button class="openModalBtn">Add New Student</button>
  <button class="rf search">search</button>
  <input type="text" name="searchname" class="rf searchname" required>
  <table class="studentTable">
    <thead>
      <tr>
        <th><input type="checkbox" class="selectAll"></th>
        <th>ID</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Hobbies</th>
        <th>Age</th>
        <th>Phone</th>
        <th>Emil</th>
        <th>Creation Time</th>
        <th>Modification Time</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <!-- Student rows will be added dynamically here -->
    </tbody>
  </table>

  <!-- 添加/修改学生信息的弹框 -->
  <div class="studentModal modal">
    <div class="modal-content">
      <h3 class="modalTitle">Add New Student</h3>
      <form class="studentForm">
        <input type="hidden" class="studentIdToEdit"> <!-- Hidden input to hold ID for editing -->

        <label for="studentName">Name</label>
        <input type="text" name="name" class="studentName" required>

        <label for="studentGender">Gender</label>
        <select name="gender" class="studentGender" required>
          <option value="Male">Male</option>
          <option value="Female">Female</option>
        </select>

        <label for="studentHobbies">Hobbies</label>
        <input type="text" name="hobbies" class="studentHobbies" required>

        <label for="studentAge">Age</label>
        <input type="number" name="age" class="studentAge" required>

        <label for="studentPhone">Phone</label>
        <input type="number" name="phone" class="studentPhone" required>

        <label for="studentEmail">Emil</label>
        <input type="text" name="email" class="studentEmail" required>

        <button type="submit" class="saveStudentBtn">Save Student</button>
      </form>
    </div>
  </div>

  <script>
    // Initial student data
    // 定义初始学生数据 使用对象储存
    // const students = [
    //   { id: 1, name: 'Alice', gender: 'Female', hobbies: 'Reading', age: 20, phone: 13513513512, email: '114514@133.com', cretime: '', modtime: '' },
    //   { id: 2, name: 'Bob', gender: 'Male', hobbies: 'Sports', age: 22, phone: 13800138000, email: "bob@example.com", cretime: '', modtime: '' },
    //   { id: 3, name: 'Charlie', gender: 'Male', hobbies: 'Gaming', age: 21, phone: 13900139000, email: "charlie@example.com", cretime: '', modtime: '' }
    // ];
    // 从本地json读取数据
    const students = JSON.parse(localStorage.getItem('students'))
    // Flag to check if editing
    // 更新/创建标记，true为更新表单，false为创建新学生。
    let isEditing = false;

    // 初始化创建时间
    // function ResetTime() {
    //   students.forEach((item) => {
    //     item.cretime = getFormattedCurrentDateTime();
    //     item.modtime = getFormattedCurrentDateTime();
    //   })
    // }
    // ResetTime()

    // Function to render the student table
    // 打印学生表
    function renderTable() {
      const tbody = document.querySelector('.studentTable tbody');
      // 创建表格主体结构
      tbody.innerHTML = ''; // Clear the table body
      // 循环为表格填入数据
      students.forEach(student => {
        const row = document.createElement('tr');

        row.innerHTML = `
                    <td><input type="checkbox" class="selectStudent" data-id="${student.id}"></td>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.hobbies}</td>
                    <td>${student.age}</td>
                    <td>${student.phone}</td>
                    <td>${student.email}</td>
                    <td>${student.cretime}</td>
                    <td>${student.modtime}</td>
                    <td>
                        <button onclick="openEditModal(${student.id})">Edit</button>
                        <button onclick="deleteStudent(${student.id})">Delete</button>
                    </td>
                `;
        // onclick: 这是一个事件属性，当按钮被点击时，它会触发指定的 JavaScript 函数。
        // 插入表格
        tbody.appendChild(row);

        // 为单独的复选框添加事件监听器
        const selectEL = document.querySelectorAll('.selectStudent');

        selectEL.forEach(checkbox => {
          checkbox.addEventListener('change', function () {
            // 如果当前复选框未被选中，直接将“全选”复选框设置为未选中
            if (!this.checked) {
              selectAllEl.checked = false;
            } else {
              const allChecked = Array.prototype.every.call(selectEL, el => el.checked);
              selectAllEl.checked = allChecked;
            }
          });
        });

      }
      )
    }
    // Function to handle "Select All" checkbox
    // 添加事件，change 事件用于监听表单元素的值变化，用于更改表单内容。
    // 选中所有复选框
    // 为全选复选框添加事件监听器
    // 为“全选”复选框添加事件监听器
    const selectAllEl = document.querySelector('.selectAll');
    selectAllEl.addEventListener('change', function () {
      const checkboxes = document.querySelectorAll('.selectStudent');
      checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked; // 更新所有单个复选框的状态
      });
    });
    // 获取时间样式
    function getFormattedCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    // Function to open the modal for editing student information
    // 保存修改的表单数据
    function openEditModal(id) {
      const student = students.find(s => s.id === id);
      if (student) {
        document.querySelector('.modalTitle').textContent = 'Edit Student';
        document.querySelector('.studentIdToEdit').value = student.id;
        document.querySelector('[name="name"]').value = student.name;
        document.querySelector('[name="gender"]').value = student.gender;
        document.querySelector('[name="hobbies"]').value = student.hobbies;
        document.querySelector('[name="age"]').value = student.age;
        document.querySelector('[name="phone"]').value = student.phone;
        document.querySelector('[name="email"]').value = student.email;
        document.querySelector('.studentModal').style.display = 'block';
        isEditing = true;
      }
    }
    // Function to handle form submission
    // 'submit' 事件通常用于监听表单（<form> 元素）提交的行为。当表单被提交时，'submit' 事件会被触发。
    // 在表单提交之后判断是新建学生档案还是更新现有表单。
    document.querySelector('.studentForm').addEventListener('submit', function (event) {
      event.preventDefault(); // Prevent default form submission
      const formData = new FormData(this);
      const data = Object.fromEntries(formData.entries());
      const id = document.querySelector('.studentIdToEdit').value;
      const phoneTF = /^(?:(?:\+|00)86)?1\d{10}$/;
      const emailTF = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      // 如果更新标记为true，则更新现有表单
      if (data.name && data.gender && data.hobbies && data.age && phoneTF.test(data.phone) && emailTF.test(data.email)) {
        if (isEditing) {
          // Update existing student
          const student = students.find(s => s.id === parseInt(id));
          if (student) {
            student.name = data.name;
            student.gender = data.gender;
            student.hobbies = data.hobbies;
            student.age = parseInt(data.age);
            student.phone = data.phone;
            student.email = data.email;
            student.modtime = getFormattedCurrentDateTime();
            localStorage.setItem('students', JSON.stringify(students))
          }
          isEditing = false;
        } else {
          // Add new student
          // 增加新学生
          students.push({
            id: students.length ? students[students.length - 1].id + 1 : 1,
            name: data.name,
            gender: data.gender,
            hobbies: data.hobbies,
            age: parseInt(data.age),
            phone: data.phone,
            email: data.email,
            cretime: getFormattedCurrentDateTime(),
            modtime: getFormattedCurrentDateTime(),
          });
          localStorage.setItem('students', JSON.stringify(students))
        }
        // 插入修改之后的表单
        renderTable();
        document.querySelector('.studentModal').style.display = 'none';
        clearModal();
      } else {
        alert('Please fill in all fields.');
      }
    });

    // Function to clear modal inputs
    // 重置弹框样式
    function clearModal() {
      // .reset()重置为初始值。
      document.querySelector('.studentForm').reset();
      document.querySelector('.studentIdToEdit').value = '';
    }

    // Function to delete a student
    // 删除点击的元素
    // 首先搜索要删除的元素的id与储存的id相同的元素
    // 没有找到就返回-1，加入是否为-1的判断，如果不是-1就执行删除指令
    // .splice（index，1）从index的位置删除1个元素
    // 更新表单。
    function deleteStudent(id) {
      const index = students.findIndex(s => s.id === id);
      if (index !== -1) {
        students.splice(index, 1);
        localStorage.setItem('students', JSON.stringify(students))
        renderTable();
      }
    }

    // Open modal for adding a new student
    // 添加内容按钮，为按钮添加点击事件，点击之后将.studentModal的显示类型改为block。
    // .textContent: 这是一个属性，用于获取或设置元素的文本内容。当你给它赋值时，它会替换掉元素内的现有文本。
    document.querySelector('.openModalBtn').addEventListener('click', function () {
      document.querySelector('.modalTitle').textContent = 'Add New Student';
      document.querySelector('.studentModal').style.display = 'block';
      isEditing = false;
    });

    // Initial table rendering
    renderTable();

    // Close the modal when clicking outside of it
    // 为页面添加点击事件，当鼠标点在.studentModal之外的内容时，将.studentModal的显示模式改为none。
    window.onclick = function (event) {
      const modal = document.querySelector('.studentModal');
      if (event.target === modal) {
        modal.style.display = 'none';
        clearModal();
      }
    };


    // 通过input框搜索name来检索学生name，无关键词默认检索所有数据
    const searchEl = document.querySelector('.search')
    searchEl.addEventListener('click', () => {
      const searchnameEl = document.querySelector('[name="searchname"]')
      if (searchnameEl.value == '') {
        let studentNames = '';
        students.forEach((item) => {
          studentNames += item.name
          studentNames += ' '
        })
        alert(studentNames)
      } else {
        students.forEach((item) => {
          if (searchnameEl.value == item.name) {
            document.querySelector('.modalTitle').textContent = 'Search Student';
            SearchStudent(item.id)
          }
        })
      }
    })
    function SearchStudent(id) {
      const student = students.find(s => s.id === id);
      if (student) {
        document.querySelector('.modalTitle').textContent = 'Search Student';
        document.querySelector('.studentIdToEdit').value = student.id;
        document.querySelector('[name="name"]').value = student.name;
        document.querySelector('[name="gender"]').value = student.gender;
        document.querySelector('[name="hobbies"]').value = student.hobbies;
        document.querySelector('[name="age"]').value = student.age;
        document.querySelector('[name="phone"]').value = student.phone;
        document.querySelector('[name="email"]').value = student.email;
        document.querySelector('.studentModal').style.display = 'block';
        isEditing = true;
      }
    }
    localStorage.setItem('students', JSON.stringify(students))

    // 0. 搞懂每一行代码 ，打上注释 √
    // 1. 修正模态框布局样式和整体bug样式，尽量让按钮 Input框美观些（1）提示：盒子模型计算 √
    // 2. 学生信息增加手机号和邮箱字段列 并在添加和修改的时候验证手机号和邮箱格式-正则    √
    // 3. 学生信息增加 创建时间和修改时间列 格式【YYYY-MM-DD HH:mm:ss】 √
    // 4. 列表的右上角增加 input框，搜索按钮，可以使用 name 检索数据，无检索关键词直接点击搜索按钮则默认检索所有数据  √
    // 5. 讲学生信息存入 localStorage ，使用JSON格式，关闭打开浏览器数据依然在   √
    // 6. 多选按钮样式和实际选择数据同步（可放最后） √

  </script>

</body>

</html>